package com.xjj.dbfs;

public class M0200NumberOfIslands {

    boolean[][] checked;

    int[] xArr = {0, 0, 1, -1};

    int[] yArr = {1, -1, 0, 0};

    public int numIslands(char[][] grid) {
        checked = new boolean[grid.length][grid[0].length];
        int count = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                // 进入没检查过的岛屿
                if (grid[i][j] == '1' && !checked[i][j]) {
                    visitGrid(i, j, grid);
                    count++;
                }
            }
        }
        return count;
    }

    private void visitGrid(int i, int j, char[][] grid) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] != '1' || checked[i][j]) {
            return;
        }
        checked[i][j] = true;
        for (int k = 0; k < xArr.length; k++) {
            visitGrid(i + xArr[k], j + yArr[k], grid);
        }
    }
}
